<template>
  <div class="container">
    <editForm :formConfig="formConfig" ref="editForm" :formData="editFormData"
      >
      <!-- <template #advanceShiftTime="{ editFormInfo }">
        <div class="dayInput">
          <el-input-number
            style="flex: 4; margin-right: 20px"
            size="mini"
            v-model="editFormInfo.advanceShiftTime"
            :step="1"
            :min="0"
            :disabled="unEdit"
            controls-position="right"
            placeholder="请输入"
            class="w100"
          ></el-input-number>
          <el-select
            style="flex: 1"
            size="mini"
            v-model="editFormInfo.advanceShiftUnit"
            placeholder="请选择"
            :disabled="unEdit"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </template> -->
    </editForm>
    <div class="tableList">
      <div class="add">
        <span>班别列表</span>
        <el-button
          size="mini"
          icon="el-icon-plus"
          plain
          v-if="!unEdit"
          @click="addRow"
        >
          新增
        </el-button>
        <el-button
          size="mini"
          icon="el-icon-edit"
          plain
          v-if="!unEdit"
          @click="edit"
        >
          编辑
        </el-button>
      </div>
      <div class="table">
        <el-table
          class="sonTable"
          :header-cell-style="{ color: '#000' }"
          border
          stripe
          :data="sonTableData"
          size="mini"
          ref="editTable"
        >
          <el-table-column
            type="index"
            width="60"
            label="序号"
          ></el-table-column>
          <el-table-column
            label="班别名称"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                class="tableInput"
                size="mini"
                v-model="scope.row.name"
                v-if="scope.row.isEdit"
              >
              </el-input>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否空白班" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.blanked"
                placeholder="请选择"
                size="mini"
                v-if="scope.row.isEdit"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <span v-else>{{ scope.row.blanked ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="值班开始时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.startTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="值班时长" align="center">
            <template slot-scope="scope">
              <el-input-number
                size="mini"
                v-model="scope.row.duration"
                controls-position="right"
                @change="handleChange(scope.$index, scope.row)"
                v-if="scope.row.isEdit"
                :min="0"
                :step-strictly="true"
                :step="0.5"
              ></el-input-number>
              <span v-else>{{ scope.row.duration }}</span>
            </template>
          </el-table-column>
          <el-table-column label="值班结束时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" prop="operate">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="() => deleteOnce(scope.row, scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { queryClassPlanDetail } from "@/api/operationManagement/runningSchedule.js";
export default {
  props: {
    id: {
      type: String,
      default: "",
    },
    unEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "方案名称",
            prop: "name",
            type: "text",
            span: 12,
            placeholder: "请选择或直接输入",
            disabled: false,
            required: true,
          },
          {
            label: "值班单位",
            prop: "deptName", //多选时，字段要为数组类型
            propArr: "deptArr",
            idsStr: "deptId",
            type: "dept-select", //类型
            option: [],
            multiple: false,
            disabled: false,
            methods: (obj) => {},
            span: 12,
          },
          {
            label: "值班人员类型",
            prop: "staffType",
            type: "select",
            span: 12,
            placeholder: "请选择",
            required: true,
            selectOption: this.$store.getters.dirtData("operation_staff_type"),
          },
          {
            label: "值班开始时间",
            prop: "startTime",
            type: "time",
            span: 12,
            required: false,
            disabled: false,
            valueFormat: "HH:mm",
            pickerOptions: {
              format: "HH:mm",
            },
            methods: (val) => {
              this.editFormData.startTime = val;
              this.changeTime(val);
            },
          },
          // {
          //   label: "提前交班时间",
          //   prop: "advanceShiftTime",
          //   type: "text",
          //   span: 12,
          //   required: false,
          //   disabled: false,
          //   methods: (val) => {},
          // },
        ],
      },
      //弹出框表单数据
      editFormData: {},
      sonTableData: [],
      timeOptions: this.$store.getters.dirtData("operation_advance_unit"),
      options: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    };
  },
  created() {
    if (this.id != "") {
      this.getDetail(this.id);
    } else {
      this.editFormData = {
        // advanceShiftTime: 15,
        // advanceShiftUnit: "0",
        deptName: this.$store.getters.currentOrgInfo.name,
        deptId: this.$store.getters.currentOrgInfo.id,
      };
      let option = [
        {
          label: this.editFormData.deptName,
          value: this.editFormData.deptId,
          id: this.editFormData.deptId,
        },
      ];
      setTimeout(() => {
        this.$refs.editForm.setItemOption("deptName", option);
        this.$refs.editForm.setFormItem("deptArr", this.editFormData.deptId);
      }, 0);
      this.sonTableData = [];
    }
  },
  watch: {
    id: {
      handler(val) {
        this.getDetail(val);
      },
    },
  },
  methods: {
    //获取班别方案详情
    getDetail(id) {
      queryClassPlanDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.editFormData = res.data;
          let option = [
            {
              label: this.editFormData.deptName,
              value: this.editFormData.deptId,
              id: this.editFormData.deptId,
            },
          ];
          setTimeout(() => {
            this.$refs.editForm.setItemOption("deptName", option);
            this.$refs.editForm.setFormItem(
              "deptArr",
              this.editFormData.deptId
            );
          }, 0);
          let data = JSON.parse(JSON.stringify(res.data.items));
          data.forEach((item) => {
            item.isEdit = false;
          });
          this.sonTableData = data;
          this.handleChange(0, this.sonTableData[0]);
        }
      });
    },
    //添加一行
    addRow() {
      if (!this.editFormData.startTime) {
        this.$alert("值班开始时间不能为空", "", {
          confirmButtonText: "确定",
          center: true,
        });
      } else {
        let len = this.sonTableData.length;
        let startTime = "";
        let name = "";
        let rowIndex = 0;
        if (len == 0) {
          startTime = this.editFormData.startTime;
        } else {
          rowIndex = this.sonTableData[len - 1].id + 1;
          startTime = this.sonTableData[len - 1].endTime;
        }
        let obj = {
          name: name,
          isEdit: true,
          blanked: 0,
          startTime: startTime,
          duration: 8,
          endTime: this.computedTime(startTime, 8),
        };
        this.sonTableData.push(obj);
      }
    },
    //点击编辑
    edit() {
      this.sonTableData.forEach((item) => {
        item.isEdit = true;
      });
    },
    //删除一行
    deleteOnce(row, index) {
      this.sonTableData.splice(index, 1);
    },
    //响应改变时间
    changeTime(val) {
      this.sonTableData.forEach((item, index, arr) => {
        if (index == 0) {
          item.startTime = val;
          item.endTime = this.computedTime(item.startTime, item.duration);
        } else {
          item.startTime = arr[index - 1].endTime;
          item.endTime = this.computedTime(item.startTime, item.duration);
        }
      });
    },
    //计算班别结束时间
    computedTime(start, interval) {
      let countDay = 1;
      if (start.indexOf("(") != -1) {
        let min = start.indexOf("第") + 1;
        let max = start.indexOf("天");
        countDay = parseInt(start.slice(min, max));
      }
      let time = start.split(":");
      let hour = (parseInt(time[0]) + parseInt(interval)) % 24;
      let day =
        Math.floor((parseInt(time[0]) + parseInt(interval)) / 24) + countDay;
      let mimite = time[1].split("(")[0];
      let endTime;
      if (parseInt(interval) < interval) {
        mimite = (parseInt(time[1]) + 30) % 60;
        if (mimite == 0) {
          mimite = "00";
        }
        if (parseInt(time[1]) + 30 - 60 >= 0) {
          hour += 1;
        }
      }
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (day > 1) {
        endTime = `${hour}:${mimite}(第${day}天)`;
      } else {
        endTime = `${hour}:${mimite}`;
      }
      return endTime;
    },
    //时长改变
    handleChange(index, row) {
      let endTime = this.computedTime(row.startTime, row.duration);
      this.sonTableData[index].endTime = endTime;
      for (let i = index + 1; i < this.sonTableData.length; i++) {
        this.sonTableData[i].startTime = this.sonTableData[i - 1].endTime;
        this.sonTableData[i].endTime = this.computedTime(
          this.sonTableData[i].startTime,
          this.sonTableData[i].duration
        );
      }
    },
    //校验表格数据
    checkForm(data) {
      let isempty = false;
      let len = data.items.length;
      data.items.forEach((item) => {
        if (item.name == "") {
          isempty = true;
        }
      });
      if (len === 0) {
        this.$message("至少需要添加一个班别");
        return false;
      } else if (isempty) {
        this.$alert("班别名称不能为空", "", {
          confirmButtonText: "确定",
          center: true,
        });
        return false;
      } else if (data.items[0].startTime != data.items[len - 1].endTime) {
        this.$alert("最后一班的结束时间与一班的开始时间必须一致", "", {
          confirmButtonText: "确定",
          center: true,
        });
        return false;
      } else {
        return true;
      }
    },
    //保存
    async getFormData() {
      try {
        let formData = await this.$refs.editForm.getFormData();
        formData.items = JSON.parse(JSON.stringify(this.sonTableData));
        formData.items.forEach((item) => {
          delete item.isEdit;
          item.startTime = item.startTime.split("(")[0];
          item.endTime = item.endTime.split("(")[0];
          return item;
        });
        if (this.checkForm(formData)) {
          return formData;
        }
      } catch (error) {}
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  padding: 10px;
  .tableList {
    height: 100%;
    margin-top: 20px;
    .add {
      margin: 10px 0;
      display: flex;
      span {
        margin: 0 20px 0 32px;
      }
      span::before {
        content: "*";
        color: red;
        margin-right: 4px;
      }
    }
    .table {
      margin-left: 120px;
    }
  }
  .dayInput {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>